<template>
    <div class="template-group-label" v-loading="loading">
        <div class="top">
            <div class="title">已选{{ chooseData.length }}个</div>
            <div class="item-list">
                <el-button
                    v-for="(item, i) in chooseData"
                    :key="i"
                    class="relative"
                    size="medium">
                    {{ item.name }}
                    <i class="el-icon-close absolute top-0 right-0" @click="onDelChoose(item, i)"></i>
                </el-button>
            </div>

            <div class="search">
                <el-input
                    v-model="form.name"
                    size="small"
                    class="input-width mr-2"
                    placeholder="请输入学习路径/学习主题进行搜索"></el-input>
                <el-button size="small" type="primary" @click="fetchData">搜索</el-button>
                <el-button size="small" type="primary" @click="onReset">重置</el-button>
            </div>
        </div>

        <div class="content" v-if="my.company_id">
            <div class="title">自建的内容</div>

            <div class="selection" v-for="(item, i) in companyData" :key="i">
                <!-- 主题模块 -->
                <div class="item">
                    <div class="item-title flex-wrap">
                        <div class="bg">
                            {{ item.label_name ? item.label_name : '单个学习主题' }}
                        </div>
                    </div>
                    <div class="sum">
                        可选工作场景主题 {{ item.child }} 个
                        <i v-if="item.label_describe" class="line"></i>
                        {{ item.label_describe }}
                    </div>

                    <div class="check-box">
                        <el-checkbox
                            @change="moreSelect($event, item)"
                            v-model="item.checked">全选</el-checkbox>
                    </div>

                    <el-collapse v-model="activeNames">
                        <el-collapse-item
                            v-for="(cot, c) in item.category_list"
                            :key="c"
                            :name="cot.index">
                            <template slot="title">
                                <el-checkbox
                                    @change="handleCheckAll($event, cot, item)"
                                    v-model="cot.checked"></el-checkbox>
                                {{ cot.category_name }} {{ cot.course_list.length }} 个
                            </template>

                            <div class="collapse-box">
                                <template v-for="(btn, b) in cot.course_list">
                                    <el-tooltip placement="bottom-start" :open-delay="1000" :key="b">
                                        <div
                                            @mouseover="getNumber(btn)"
                                            :class="`collapse-item ${ btn.checked ? 'active' : '' }`"
                                            @click="onSelect(btn, cot, item)">{{ btn.name }}</div>
                                        <div class="content" slot="content">
                                            <GroupComponent
                                                @toView="toView(btn)"
                                                :show="btn.show"
                                                :id="btn.id"
                                                :content="btn.context"/>
                                        </div>
                                    </el-tooltip>
                                </template>
                            </div>
                        </el-collapse-item>
                    </el-collapse>
                </div>
            </div>
        </div>

        <div class="content">
            <div class="title">来自msup提供的内容</div>

            <div class="selection" v-for="(item, i) in adminData" :key="i">
                <!-- 主题模块 -->
                <div class="item">
                    <div class="item-title flex-wrap">
                        <div class="bg">
                            {{ item.label_name ? item.label_name : '单个学习主题' }}
                        </div>
                    </div>
                    <div class="sum">
                        可选工作场景主题 {{ item.child }} 个
                        <i v-if="item.label_describe" class="line"></i>
                        {{ item.label_describe }}
                    </div>

                    <div class="check-box">
                        <el-checkbox
                            @change="moreSelect($event, item)"
                            v-model="item.checked">全选</el-checkbox>
                    </div>

                    <el-collapse v-model="activeNames">
                        <el-collapse-item
                            v-for="(cot, c) in item.category_list"
                            :key="c"
                            :name="cot.index">
                            <template slot="title">
                                <el-checkbox
                                    @change="handleCheckAll($event, cot, item)"
                                    v-model="cot.checked"></el-checkbox>
                                {{ cot.category_name }} {{ cot.course_list.length }} 个
                            </template>

                            <div class="collapse-box">
                                <template v-for="(btn, b) in cot.course_list">
                                    <el-tooltip placement="bottom-start" :open-delay="1000" :key="b">
                                        <div
                                            @mouseover="getNumber(btn)"
                                            :class="`collapse-item ${ btn.checked ? 'active' : '' }`"
                                            @click="onSelect(btn, cot, item)">{{ btn.name }}</div>
                                        <div class="content" slot="content">
                                            <GroupComponent
                                                @toView="toView(btn)"
                                                :show="btn.show"
                                                :id="btn.id"
                                                :content="btn.context"/>
                                        </div>
                                    </el-tooltip>
                                </template>
                            </div>
                        </el-collapse-item>
                    </el-collapse>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import { Collapse, CollapseItem, Tooltip } from 'element-ui';
import GroupComponent from './GroupComponent.vue';

export default {
    components: {
        ElCollapse: Collapse,
        ElCollapseItem: CollapseItem,
        ElTooltip: Tooltip,
        GroupComponent,
    },
    data() {
        return {
            loading: false,
            activeNames: [],

            adminData: [],
            companyData: [],

            chooseData: [],

            form: {
                companyId: '',
                name: '',
            },

            templateData: {
                title: '',
                describe: '',
                is_template: false,
                course_list: [],
            },
            course_list: [],
        };
    },
    computed: {
        my() {
            return this.$store.state.my;
        },
    },
    watch: {
        chooseData(val) {
            this.$emit('input', val);
        },
    },
    methods: {
        /**
         * 删除已选中的数据
         *
         * @params e 选中的数据
         * @params i 数据的下标
        */
        onDelChoose(e, i) {
            const chooseData = [...this.chooseData];
            chooseData.splice(i, 1);

            this.delChooseFn(e, 'adminData');
            this.delChooseFn(e, 'companyData');

            this.chooseData = chooseData;
        },
        delChooseFn(e, dataText) {
            const arrData = this[dataText] || [];

            for (const item of arrData) {
                for (const val of item.category_list) {
                    for (const obj of val.course_list) {
                        // 比对唯一id
                        if (e.id === obj.id) {
                            obj.checked = false;
                            if (val.checked) val.checked = false;
                            if (item.checked) item.checked = false;
                        }
                    }
                }
            }

            this[dataText] = arrData;
        },

        /**
         * 选中数据
         * @params e 选中的数据
         * @params child 子级数据
         * @params parent 父级数据
        */
        onSelect(e, child, parent) {
            const chooseData = this.chooseData;

            if (!chooseData.length) {
                chooseData.push(e);
                e.checked = true;
            } else {
                let index = 0;

                chooseData.forEach((v, i) => {
                    if (e.id === v.id) index = i + 1;
                });

                if (index) {
                    chooseData.splice(index - 1, 1);
                } else chooseData.push(e);
                e.checked = !index;
            }

            this.checkedFn(child, 'course_list');
            this.checkedFn(parent, 'category_list');
        },

        /**
         * 场景全选
         * @params e 是否选中
         * @params parent 父级数据
        */
        moreSelect(e, parent) {
            const arrData = parent.category_list;

            if (arrData && arrData.length) {
                if (e) {
                    parent.checkedArr = arrData;
                } else parent.checkedArr = [];

                for (const item of arrData) {
                    this.handleCheckAll(e, item);
                    item.checked = e;
                }
            }
        },

        /**
         * 主题全选
         *
         * @params e 是否选中
         * @params child 子级数据
         * @params parent 父级数据
        */
        handleCheckAll(e, child, parent) {
            const arrData = child.course_list || [];

            let chooseData = [...this.chooseData];
            if (!chooseData.length && e) chooseData = [...arrData];
            if (chooseData.length) {
                for (const item of arrData) {
                    let index = 0;

                    chooseData.forEach((v, i) => {
                        // 没有唯一id，比对数据字符串,是否是同一数据
                        if (item.id === v.id) return index = i + 1;
                    });

                    if (!index && e) chooseData.push(item);
                    if (index && !e) chooseData.splice(index - 1, 1);
                }
            }

            child.course_list.map(item => {
                item.checked = e;
                return item;
            });

            if (e) {
                child.checkedArr = arrData;
            } else child.checkedArr = [];

            this.chooseData = chooseData;

            if (parent) this.checkedFn(parent, 'category_list');
        },

        /**
         * 设置全选的checkbox选中状态
        */
        checkedFn(obj, arrText) {
            let pCheck = 0;
            const pArr = obj[arrText] || [];

            for (const item of pArr) {
                if (item.checked) pCheck += 1;
            }

            if (!pCheck || (pCheck && pCheck !== pArr.length)) obj.checked = false;
            if (pCheck === pArr.length) obj.checked = true;
        },

        /**
         * 重置搜索条件
        */
        onReset() {
            this.form.name = '';
            this.activeNames = [];
            this.fetchData();
        },

        /**
         * 获取数据
        */
        fetchData() {
            if (this.my && this.my.company_id) this.form.companyId = this.my.company_id;

            this.loading = true;
            API.get('label/courseData', {params: this.form}).then(res => {
                const adminData = res.admin_list || [];
                const companyData = res.company_list || [];

                let otherAdmin = [];
                let otherCompany = [];
                for (const item of adminData) {
                    otherAdmin = [...otherAdmin, ...item.label_list];
                }
                for (const item of companyData) {
                    otherCompany = [...otherCompany, ...item.label_list];
                }

                const adminIds = this.fetchDataOption(otherAdmin, 'adminData');
                const companyIds = this.fetchDataOption(otherCompany, 'companyData');

                // 去重
                const chooseData = [...adminIds, ...companyIds].map(item => JSON.stringify(item));
                this.chooseData = [...new Set(chooseData)].map(item => JSON.parse(item));
            }).finally(() => this.loading = false);
        },

        /**
         * 数据结构处理
         * @params listArr 传入的主数据
         * @params dataText 需要赋值的数据字段名
         * @return ids 编辑时，已选中的数据
        */
        fetchDataOption(listArr, dataText) {
            const chooseIds = this.$attrs.value;
            const ids = [];
            const arrData = [...listArr];

            for (const item of arrData) {
                item.child = 0;
                item.checked = false;
                if (!item.category_list || !item.category_list.length) continue;

                /**
                 * 已选中的子级数量
                 * */
                let itemCheckNum = 0;
                for (const val of item.category_list) {
                    if (!val.course_list || !val.course_list.length) continue;
                    val.checked = false;

                    item.child += val.course_list.length;

                    /**
                     * 已选中的数量
                     * */
                    let valCheckNum = 0;
                    // 设置选中状态字段
                    val.course_list.map(vItem => {
                        vItem.show = false;

                        // 获取数据时获取之前已设置的数据
                        for (const j of chooseIds) {
                            if (vItem.id === j.id) {
                                ids.push({
                                    id: vItem.id,
                                    name: vItem.name,
                                    checked: true,
                                });
                                vItem.checked = true;
                                valCheckNum += 1;
                            }
                        }

                        return vItem;
                    });

                    if (valCheckNum === val.course_list.length) {
                        val.checked = true;
                        itemCheckNum += 1;
                    }
                }

                item.checked = !!(itemCheckNum === item.category_list.length);
            }

            this[dataText] = arrData;

            return ids;
        },

        /**
         * 数据是否选中
         * @param val 数据，<object>
         * @return className string
        */
        selected(val) {
            if (!val) return '';
            const chooseData = this.chooseData;
            for (const item of chooseData) {
                if (item.id === val.id) return 'active';
            }
            return '';
        },

        /**
         * 获取节点数
        */
        getNumber(e) {
            if (!e.show) e.show = true;
        },

        toView(e) {
            this.$router.push({
                name: 'LabelManage.Preview',
                params: {
                    id: e.id,
                },
            });
        },
    },
    mounted() {
        this.fetchData();
    },
};
</script>

<style lang="scss">
$marginL: 130px;
$color: rgb(64, 158, 255);
$color2: rgb(221, 223, 230);

.template-group-label {
    .input-width {
        max-width: 300px;
    }

    .top {
        margin-left: $marginL;

        .title {
            margin-bottom: 25px;
        }

        .item-list {
            height: 130px;
            overflow-y: auto;

            .el-button {
                padding: 12px 45px;
                border-radius: 5px;
                margin: 0 10px 10px 0;

                &:focus, &:hover {
                    color: inherit;
                    background: white;
                    border: 1px solid #DCDFE6;
                }
            }

            .el-button+.el-button {
                margin-left: 0;
            }

            i {
                width: 27px;
                height: 27px;
                margin: -1px -1px 0 0;
                text-align: right;
                color: white;
                font-size: 16px;
                font-weight: 600;
                border-radius: 0 5px 0 0;
                background: linear-gradient(45deg, #fff 0%, #fff 49%, #ff445c 50%, #ff445c 100%);
            }
        }

        .search {
            border-top: 1px solid $color2;
            padding-top: 50px;
            margin-top: 50px;
        }
    }

    .content {
        margin-top: 30px;

        .check-box {
            margin-bottom: 15px;
        }

        .el-checkbox__inner {
            border-radius: 50%;
        }

        .el-checkbox:last-of-type {
            margin-right: 10px;
            padding-left: 10px;
        }

        .el-checkbox__input .el-checkbox__inner::after {
            position: absolute;
            left: 50%;
            top: 50%;
            transform: translate(-50%, -50%);
            width: 6px;
            height: 6px;
            border: none;
        }

        .el-checkbox__input.is-checked .el-checkbox__inner {
            background-color: white;

            &::after {
                background: #409EFF;
                border-radius: 50%;
            }
        }

        .el-collapse-item__header,
        .el-collapse,
        .el-collapse-item__wrap {
            border: none;
        }

        .el-collapse-item__wrap {
            overflow: visible;
        }

        .el-collapse-item__header {
            color: #2d70ae;
            font-size: 20px;
            padding-right: 25px;
            box-sizing: border-box;
        }

        .el-collapse-item {
            margin-bottom: 10px;
        }

        .el-collapse-item__arrow {
            width: 30px;
            height: 30px;
            background: url('~@/assets/images/template/open.png') no-repeat;
            background-size: contain;
        }

        .el-collapse-item__arrow.is-active {
            background: url('~@/assets/images/template/close.png') no-repeat;
            background-size: contain;
            transform: rotate(0);
        }

        .el-icon-arrow-right:before {
            content: '';
        }

        .el-collapse-item__content {
            padding-top: 10px;
            padding-right: 10px;
            padding-bottom: 0;
        }

        .title {
            font-size: 14px;
            color: rgb(155, 155, 155);
            padding: 14px 0 14px $marginL;
            background: rgb(250, 250, 250);
            margin-bottom: 17px;
        }

        .selection {
            padding: 24px 100px 20px 130px;
            box-sizing: border-box;
            box-shadow: 0 0 4px 1px $color2;
            margin: 10px 0;
        }

        .item {
            &-title {
                display: flex;
                align-items: flex-end;
                margin-bottom: 15px;

                .bg {
                    font-size: 40px;
                    color: #606266;
                    margin-right: 26px;
                }

            }

            .sum {
                font-size: 14px;
                color: #b0b4bc;
                margin-bottom: 30px;

                .line {
                    width: 100px;
                    display: inline-block;
                    margin: 0 4px 3px 4px;
                    border-top: 2px solid #cecdcd;
                }
            }

            &-desc {
                font-size: 14px;
                color: rgb(96, 98, 102);
                margin-bottom: 20px;
            }

            .collapse-box {
                display: flex;
                flex-wrap: wrap;
            }

            .collapse-item {
                display: flex;
                justify-content: center;
                align-items: center;
                min-width: 230px;
                min-height: 44px;
                text-align: center;
                box-sizing: border-box;
                padding: 0 12px;
                border: 1px solid $color2;
                border-radius: 5px;
                margin-right: 25px;
                margin-bottom: 23px;
                cursor: pointer;

                &.active {
                    background: $color;
                    color: white;
                }

                &:hover {
                    box-shadow: 0 0 8px 2px $color2;
                }
            }
        }
    }

    .el-collapse-item__header {
        background: rgba($color: #2d70ae, $alpha: .05);
    }
}

.el-tooltip__popper.is-dark {
    background: rgba($color: #36383c, $alpha: .8);
}
</style>
